/**
 * 预览页
 * @type Page
 * @screen 1400w
 * @frames web
 */
import React from 'react';
import { Page, AtIcon, View, Text, Modal } from '@appthen/react';
import { Input, Button, InputNumber } from '@appthen/antd';
import RichTextComponent from '/src/pages/component/RichTextComponent';
import FileUploadWebVersion from '/src/pages/component/FileUploadWebVersion';
import './previewPage.css';

class IProps { }

/*
 * 数据与接口请求定义
 */
class IState {
  formFields?: {
    /* @example 1755831617450 */id: string,
    /* @example 1 */deviceId: number,
    /* @example false */required: boolean,
    /* @example false */defaultSelected: boolean,
    /* @example false */calculatePrice: boolean,
    /* @example 0 */price: number,
    options: string,
    /* @example 样品是否容易易氧化需要手套箱制样测试 */name: string,
    /* @example xps_zidendhrwwzzqlstxszlt */code: string,
    /* @example select */type: string,
    /* @example 容易氧化以及接触大气变质的样品，可选择手套箱制样测试，防止样品氧化/变质，即要求同学真空包装样品。无法回收手套箱制样的样品，必然暴露大气。 */description: string,
    /* @example 否 */defaultValue?: string,
    linkageRules: string,
    /* @example 请输入块状/薄膜测试面说明 */placeholder?: string,
    /* @example true */visible?: boolean,
    /* @example 3 */baseQuantity?: number,
    /* @example 20 */basePrice?: number,
    /* @example 20 */unitPrice?: number,
    /* @example 6 */order?: number,
  }[];
  testSchema?: {
    /* @example object */type: string,
    properties: string,
    required: string,
    linkageRules: string,
  }[];
  /* 表单 */
  formData?: any;
  /* 表单验证 */
  validationErrors?: any;
  /* 隐藏表单项 */
  hiddenFields?: any;
  testdata?: {
    /* @example equipment215_svdua */fieldName: string,
    fieldSchema: string,
    fieldValue: any,
    /* @example true */isRequired: boolean,
  }[];
  yuansu?: any[];
  /* 后台预览/客户端 */
  mode?: string;

  @DataSource({
    uri: this.constants.HostDomain + "/app/product/device/calculatePrice",
    contentType: "JSON",
    method: "POST",
    isCors: true,
    isInit: false
  })
  calculateprice?: any;
  totalPrice?: number;
  obtainFormData?: any[];
  isSkipTitle?: string;
  samplesData?: {
    /* @example 0 */index: number,
    /* @example A */sampleId: string,
    formData: any,
    obtainFormData: any,
  }[];

  @DataSource({
    uri: this.constants.HostDomain + "/app/product/device/info/:id",
    contentType: "JSON",
    method: "GET",
    isCors: true,
    isInit: false
  })
  getDeail?: {
    /* @example 1001 */code: number,
    /* @example /admin/product/device/info Not Found */message: string,
  };
}

class Document extends React.Component<IProps, IState> {
  state = {
    formFields: [],
    testSchema: [],
    formData: {},
    validationErrors: {},
    hiddenFields: {},
    testdata: [],
    yuansu: [],
    mode: 'admin',
    calculateprice: {},
    totalPrice: 0,
    obtainFormData: [],
    isSkipTitle: '',
    samplesData: [
      {
        index: 0,
        sampleId: 'A',
        formData: {},
        obtainFormData: [],
        yuansu: [],
        hiddenFields: {},
        validationErrors: {},
      },
    ],
  };

  /**
   * 预览表单初始化
   */
  previewFormInitialization() {
    const formData = {};
    const { properties = {} } = this.state.testSchema;
    Object.keys(properties).forEach((fieldName) => {
      const fieldSchema = properties[fieldName];
      if (
        fieldSchema.default !== undefined &&
        fieldSchema.default !== null &&
        fieldSchema.default !== ''
      ) {
        formData[fieldName] = fieldSchema.default;
      } else {
        switch (fieldSchema.widget) {
          case 'input':
            formData[fieldName] = '';
            break;
          case 'inputNumber':
            formData[fieldName] = '';
            break;
          case 'select':
            if (fieldSchema.options) {
              const preSelectedOption = fieldSchema.options.find(
                (opt) => opt.is_selected === 1
              );
              formData[fieldName] = preSelectedOption
                ? preSelectedOption.value
                : '';
            } else {
              formData[fieldName] = '';
            }
            break;
          case 'checkboxes':
            if (fieldSchema.options) {
              const preSelectedValues = fieldSchema.options
                .filter((opt) => opt.is_selected === 1)
                .map((opt) => opt.value);
              formData[fieldName] = preSelectedValues;
            } else {
              formData[fieldName] = [];
            }
            break;
          case 'periodicTable':
            formData[fieldName] = ['C'];
            break;
          case 'file':
            formData[fieldName] = [];
            break;
          case 'richText':
            formData[fieldName] = '';
            break;
          default:
            if (fieldSchema.type === 'number') {
            } else if (fieldSchema.type === 'array') {
              formData[fieldName] = [];
            } else {
              formData[fieldName] = '';
            }
        }
      }
    });
    const periodicTableField = Object.keys(
      this.state.testSchema.properties || {}
    ).find(
      (key) => this.state.testSchema.properties[key].widget === 'periodicTable'
    );
    const initialSample = {
      index: 0,
      sampleId: 'A',
      formData: formData,
      // 表单数据
      obtainFormData: [],
      // 处理后的表单数据
      yuansu: formData[periodicTableField] || ['C'],
      // 元素周期表数据
      hiddenFields: {},
      // 隐藏字段状态
      validationErrors: {}, // 验证错误状态
    };

    this.setState(
      {
        samplesData: [initialSample],
      },
      () => {
        // 6. 调用方法时传入sampleIndex = 0
        this.obtainFormData(0); // 传入样品索引0
        this.calculateThePrice(); // 计算所有样品的价格
        this.handleTheLinkageRules(0, formData, formData); // 传入样品索引0
      }
    );
  }

  /**
   * 页面加载后执行
   */
  componentDidMount() {
    // console.log(this.utils.message)
    this.dataSourceMap['getDeail']
      ?.load({
        __pathParams: {
          id: this.state.deviceInfo?.id || 427,
        },
      })
      .then((res) => {
        // console.log(res。data/);
        const data = res?.data?.formConfig;

        // 对 properties 按照 order 字段进行排序
        const sortedProperties = {};
        const propertyEntries = Object.entries(data.properties);

        // 按 order 字段排序，如果没有 order 字段则放在最后
        propertyEntries.sort((a, b) => {
          const orderA = a[1].order || 999;
          const orderB = b[1].order || 999;
          return orderA - orderB;
        });

        // 重新构建排序后的 properties 对象
        propertyEntries.forEach(([key, value]) => {
          sortedProperties[key] = value;
        });

        // 更新 data 对象
        data.properties = sortedProperties;
        this.setState(
          {
            testSchema: data,
          },
          () => {
            this.previewFormInitialization();
          }
        );
      });
  }

  /**
   * 获取表单数据
   */
  obtainFormData(sampleIndex) {
    if (!this.state.testSchema || !this.state.testSchema.properties) {
      return;
    }
    const sample = this.state.samplesData[sampleIndex];
    if (!sample) return;
    let arr = Object.keys(this.state.testSchema.properties)
      .filter((fieldName) => {
        const fieldSchema = this.state.testSchema.properties[fieldName];
        if (fieldSchema.independentMode) {
          const shouldShow = this.evaluateIndependentField(
            fieldSchema,
            sample.formData
          );
          return shouldShow;
        } else {
          const isHidden = sample.hiddenFields[fieldName];
          return !isHidden;
        }
      })
      .map((fieldName) => {
        const fieldSchema = this.state.testSchema.properties[fieldName];
        const fieldValue = sample.formData[fieldName] || '';
        const isRequired = this.state.testSchema.required?.includes(fieldName);
        const hasError = sample.validationErrors[fieldName];
        return {
          fieldName,
          fieldSchema,
          fieldValue,
          isRequired,
          hasError,
        };
      });
    const newSamplesData = this.state.samplesData.map((s, index) => {
      if (index === sampleIndex) {
        return {
          ...s,
          obtainFormData: arr,
        };
      }
      return s;
    });
    console.log('🔄 obtainFormData 更新前 hiddenFields:', this.state.samplesData[sampleIndex].hiddenFields);
    this.setState({
      samplesData: newSamplesData,
    }, () => {
      console.log('🔄 obtainFormData 更新后 hiddenFields:', this.state.samplesData[sampleIndex].hiddenFields);
    });
  }

  /**
   * handleInputChange
   */
  handleInputChange({ sampleIndex, fieldName, value }) {
    const targetSampleIndex = sampleIndex !== undefined ? sampleIndex : 0;
    this.testingQuotationMode(targetSampleIndex, fieldName, value);
    console.log('onChange', targetSampleIndex, fieldName, value);
    const newSamplesData = this.state.samplesData.map((sample, index) => {
      if (index === targetSampleIndex) {
        const newFormData = {
          ...sample.formData,
          [fieldName]: value,
        };
        return {
          ...sample,
          formData: newFormData,
        };
      }
      return sample;
    });
    this.setState(
      {
        samplesData: newSamplesData,
      },
      () => {
        // ✅ 直接使用 newSamplesData 中的数据，避免状态异步问题
        const updatedFormData = newSamplesData[targetSampleIndex].formData;
        this.handleTheLinkageRules(
          targetSampleIndex,
          {
            [fieldName]: value,
          },
          updatedFormData // ✅ 使用确定更新后的表单数据
        );
        this.obtainFormData(targetSampleIndex);
        this.calculateThePrice();
      }
    );
  }

  /**
   * 通用修改数据
   */
  setStateValue(e, { field, valueField, indexs }, cb) {
    const state = {
      ...this.state,
    };
    let value = e;
    if (valueField) {
      value = valueField.split('.').reduce((obj, key) => obj && obj[key], e);
    }
    const _field =
      indexs?.length > 0
        ? field
          .replace(/\.\[\]/g, (match) => `[${indexs.shift()}].`)
          .replace('.[item]', '')
        : field;
    this.utils.setValue(state, _field, value);
    this.setState(state, cb);
  }

  /**
   * 渲染多选项
   */
  renderMultipleOptions(item) {
    const options = item?.fieldSchema?.options || [];
    const fieldValue = item?.fieldValue;

    // 处理 selectedValues
    const selectedValues = Array.isArray(fieldValue)
      ? fieldValue
      : fieldValue !== null && fieldValue !== undefined
        ? [fieldValue]
        : [];
    const data = options.map((option) => ({
      ...option,
      isSelected: selectedValues.some(
        (val) =>
          val != null &&
          option?.value != null &&
          String(val) === String(option.value)
      ),
      optionName: option?.value || '',
      isRequired: option?.is_required === 1,
    }));
    return data;
  }

  /**
   * 多选操作
   */
  multipleSelectionOperation({
    option,
    item,
    sampleIndex, // ✅ 添加sampleIndex参数
  }) {
    // 如果选项是必选的且当前已被选中，不允许取消
    if (option?.isRequired && option?.isSelected) {
      return this.utils.message.warning(`${option?.optionName} 是必选选项`);
    }

    // ✅ 如果没有传入sampleIndex，默认使用第一个样品
    const targetSampleIndex = sampleIndex !== undefined ? sampleIndex : 0;

    // ✅ 获取指定样品的数据
    const sample = this.state.samplesData[targetSampleIndex];
    if (!sample) {
      console.error(`样品索引 ${targetSampleIndex} 不存在`);
      return;
    }

    // ✅ 使用指定样品的formData
    const currentValue = sample.formData[item?.fieldName] || [];
    let newValue;
    if (!option.isSelected) {
      newValue = [...currentValue, option?.value];
    } else {
      newValue = currentValue.filter((v) => v !== option?.value);
    }

    // ✅ 调用handleInputChange时传入sampleIndex
    this.handleInputChange({
      sampleIndex: targetSampleIndex, // ✅ 传入样品索引
      fieldName: item?.fieldName,
      value: newValue,
    });
  }

  /**
   * 检查联动条件
   */
  checkTheLinkageConditions(condition, currentValue, expectedValue) {
    switch (condition) {
      case 'equals':
        // 等于条件：支持数组包含和字符串相等两种情况
        if (Array.isArray(currentValue)) {
          return currentValue.includes(expectedValue);
        } else {
          return currentValue === expectedValue;
        }
      case 'not_equals':
        // 不等于条件：支持数组不包含和字符串不相等两种情况
        if (Array.isArray(currentValue)) {
          return !currentValue.includes(expectedValue);
        } else {
          return currentValue !== expectedValue;
        }
      case 'contains':
        // 包含条件：数组包含指定值
        if (Array.isArray(currentValue)) {
          return currentValue.includes(expectedValue);
        } else {
          // 字符串包含
          return String(currentValue).includes(String(expectedValue));
        }
      case 'not_contains':
        // 不包含条件：数组不包含指定值
        if (Array.isArray(currentValue)) {
          return !currentValue.includes(expectedValue);
        } else {
          // 字符串不包含
          return !String(currentValue).includes(String(expectedValue));
        }
      case 'greater_than':
        // 大于条件：数值比较
        return Number(currentValue) > Number(expectedValue);
      case 'less_than':
        // 小于条件：数值比较
        return Number(currentValue) < Number(expectedValue);
      default:
        console.warn('未知的联动条件:', condition);
        return false;
    }
  }

  /**
   * 评估JSON格式的条件
   */
  evaluateJsonCondition(condition, formData) {
    const { field, operator, value } = condition;
    const fieldValue = formData[field];
    // console.log(`🔍 JSON条件评估: ${field} ${operator} ${value}, 当前值:`, fieldValue);
    switch (operator) {
      case 'equals':
        if (Array.isArray(fieldValue)) {
          return fieldValue.includes(value);
        } else {
          return fieldValue === value;
        }
      case 'not_equals':
        if (Array.isArray(fieldValue)) {
          return !fieldValue.includes(value);
        } else {
          return fieldValue !== value;
        }
      case 'contains':
        if (Array.isArray(fieldValue)) {
          return fieldValue.includes(value);
        } else {
          return String(fieldValue).includes(String(value));
        }
      case 'not_contains':
        if (Array.isArray(fieldValue)) {
          return !fieldValue.includes(value);
        } else {
          return !String(fieldValue).includes(String(value));
        }
      case 'greater_than':
        return Number(fieldValue) > Number(value);
      case 'less_than':
        return Number(fieldValue) < Number(value);
      case 'greater_equal':
        return Number(fieldValue) >= Number(value);
      case 'less_equal':
        return Number(fieldValue) <= Number(value);
      case 'array_length_greater':
        return Array.isArray(fieldValue) && fieldValue.length > Number(value);
      case 'array_length_less':
        return Array.isArray(fieldValue) && fieldValue.length < Number(value);
      case 'array_length_equals':
        return Array.isArray(fieldValue) && fieldValue.length === Number(value);
      default:
        console.warn('未知的JSON条件操作符:', operator);
        return false;
    }
  }

  /**
   * 解析表达式 - 独立模式使用
   */
  evaluateExpression(expression, formData) {
    try {
      // 创建一个安全的执行环境
      const context = {
        ...formData,
      };

      // 简单的表达式替换和执行
      // 支持基本的JavaScript表达式语法
      const result = new Function(
        'context',
        `
        with(context) {
          return ${expression};
        }
      `
      )(context);
      return Boolean(result);
    } catch (error) {
      console.warn('表达式解析错误:', expression, error);
      return false;
    }
  }

  /**
   * 评估独立模式字段是否显示
   */
  evaluateIndependentField(fieldSchema, formData) {
    if (!fieldSchema.displayConditions) {
      return true; // 没有条件则默认显示
    }

    // 🔧 支持三种数据格式
    if (Array.isArray(fieldSchema.displayConditions)) {
      // 旧模式：数组格式，默认OR逻辑（表达式格式）
      if (fieldSchema.displayConditions.length === 0) {
        return true;
      }
      console.log(
        '🟡 使用旧模式(表达式+OR逻辑):',
        fieldSchema.displayConditions
      );
      return fieldSchema.displayConditions.some((condition) =>
        this.evaluateExpression(condition.expression, formData)
      );
    } else if (
      fieldSchema.displayConditions.logic &&
      fieldSchema.displayConditions.conditions
    ) {
      // 检查是否为新的JSON格式
      const { logic, conditions } = fieldSchema.displayConditions;
      if (!conditions || conditions.length === 0) {
        return true;
      }

      // 检查第一个条件的格式来判断是表达式格式还是JSON格式
      const firstCondition = conditions[0];
      if (firstCondition.expression) {
        // 表达式格式（新模式但仍用表达式）
        console.log(`🟢 使用新模式(表达式+${logic}逻辑):`, conditions);
        if (logic === 'AND') {
          return conditions.every((condition) =>
            this.evaluateExpression(condition.expression, formData)
          );
        } else {
          return conditions.some((condition) =>
            this.evaluateExpression(condition.expression, formData)
          );
        }
      } else if (firstCondition.field && firstCondition.operator) {
        // JSON格式（最新格式）
        // console.log(`🔵 使用JSON格式(${logic}逻辑):`, conditions);
        if (logic === 'AND') {
          return conditions.every((condition) =>
            this.evaluateJsonCondition(condition, formData)
          );
        } else {
          return conditions.some((condition) =>
            this.evaluateJsonCondition(condition, formData)
          );
        }
      }
    }

    // 兜底：如果格式不正确，默认显示
    console.warn(
      '⚠️ displayConditions格式不正确:',
      fieldSchema.displayConditions
    );
    return true;
  }

  /**
   * 处理联动规则
   */
  handleTheLinkageRules(sampleIndex, changedValues, allValues) {
    if (!this.state.testSchema || !this.state.testSchema.linkageRules) {
      return;
    }
    const sample = this.state.samplesData[sampleIndex];
    if (!sample) return;
    let fieldsToHide = { ...sample.hiddenFields };

    console.log('🔧 联动规则调试:', {
      sampleIndex,
      changedValues,
      allValues,
      currentHiddenFields: sample.hiddenFields
    });

    const isInitializing =
      !sample.hiddenFields || Object.keys(sample.hiddenFields).length === 0;
    if (isInitializing) {
      Object.keys(this.state.testSchema.linkageRules).forEach(
        (triggerField) => {
          const rules = this.state.testSchema.linkageRules[triggerField];
          rules.forEach((rule) => {
            if (rule.targetFields && Array.isArray(rule.targetFields)) {
              rule.targetFields.forEach((targetField) => {
                fieldsToHide[targetField] = true;
              });
            }
          });
        }
      );
    } else {
    }

    const changedFieldNames = Object.keys(changedValues);

    // 🔧 修复：如果变化的字段都没有联动规则，直接返回
    const hasRulesForChangedFields = changedFieldNames.some(
      (fieldName) => this.state.testSchema.linkageRules[fieldName]
    );
    if (!hasRulesForChangedFields) {
      return;
    }

    // ... 原有的联动规则处理逻辑保持不变 ...
    // （这部分逻辑不需要修改，因为它只是处理规则逻辑，不涉及状态）

    changedFieldNames.forEach((changedFieldName) => {
      if (this.state.testSchema.linkageRules[changedFieldName]) {
        const rules = this.state.testSchema.linkageRules[changedFieldName];
        const showRuleResults = {};
        const hideRuleResults = {};
        rules.forEach((rule) => {
          const triggerValue = allValues[changedFieldName];
          const shouldTrigger = this.checkTheLinkageConditions(
            rule.triggerCondition,
            triggerValue,
            rule.triggerValue
          );

          console.log('🔍 联动规则判断:', {
            changedFieldName,
            triggerValue,
            rule: {
              triggerCondition: rule.triggerCondition,
              triggerValue: rule.triggerValue,
              action: rule.action,
              targetFields: rule.targetFields
            },
            shouldTrigger
          });
          // 根据动作类型收集结果
          if (rule.targetFields && Array.isArray(rule.targetFields)) {
            rule.targetFields.forEach((targetField) => {
              if (rule.action === 'show') {
                if (!showRuleResults[targetField]) {
                  showRuleResults[targetField] = [];
                }
                showRuleResults[targetField].push(shouldTrigger);
              } else if (rule.action === 'hide') {
                if (!hideRuleResults[targetField]) {
                  hideRuleResults[targetField] = [];
                }
                hideRuleResults[targetField].push(shouldTrigger);
              }
            });
          }
        });

        // 处理show规则
        console.log('📋 Show规则结果:', showRuleResults);
        Object.keys(showRuleResults).forEach((targetFieldName) => {
          const hasAnyShowTrigger = showRuleResults[targetFieldName].some(
            (result) => result === true
          );
          console.log(`🔍 处理show规则 ${targetFieldName}:`, {
            results: showRuleResults[targetFieldName],
            hasAnyShowTrigger,
            beforeHidden: fieldsToHide[targetFieldName]
          });
          if (hasAnyShowTrigger) {
            delete fieldsToHide[targetFieldName];
          } else {
            fieldsToHide[targetFieldName] = true;
          }
          console.log(`✅ 处理后 ${targetFieldName} hidden:`, fieldsToHide[targetFieldName]);
        });

        // 处理hide规则
        Object.keys(hideRuleResults).forEach((targetFieldName) => {
          const hasAnyHideTrigger = hideRuleResults[targetFieldName].some(
            (result) => result === true
          );
          if (hasAnyHideTrigger) {
            fieldsToHide[targetFieldName] = true;
          } else {
            delete fieldsToHide[targetFieldName];
          }
        });
      }
    });

    console.log('🎯 最终隐藏字段状态:', fieldsToHide);

    const newSamplesData = this.state.samplesData.map((s, index) => {
      if (index === sampleIndex) {
        return { ...s, hiddenFields: fieldsToHide };
      }
      return s;
    });

    console.log('🔄 更新样品数据:', {
      sampleIndex,
      oldHiddenFields: this.state.samplesData[sampleIndex].hiddenFields,
      newHiddenFields: fieldsToHide
    });

    this.setState(
      {
        samplesData: newSamplesData, // ✅ 更新samplesData数组
      },
      () => {
        console.log('✅ 状态更新完成，传入的隐藏字段:', newSamplesData[sampleIndex].hiddenFields);
        console.log('✅ 状态更新完成，实际状态中的隐藏字段:', this.state.samplesData[sampleIndex].hiddenFields);
        this.obtainFormData(sampleIndex); // ✅ 传入sampleIndex
      }
    );
  }

  /**
   * 提交表单
   */
  submitForm(event) {
    // ✅ 验证所有样品
    const { allErrors, hasAnyError } = this.formVerification();
    console.log('验证结果:', allErrors);

    // ✅ 检查是否有任何样品的错误
    if (hasAnyError) {
      // ✅ 显示第一个有错误的样品信息
      const firstSampleWithError = Object.keys(allErrors)[0]; // 获取第一个有错误的样品ID
      const firstErrorField = Object.keys(allErrors[firstSampleWithError])[0]; // 获取第一个错误字段
      const fieldSchema = this.state.testSchema?.properties[firstErrorField];
      const fieldTitle = fieldSchema?.title || firstErrorField;

      // ✅ 显示带样品组标识的错误信息
      this.utils.notification.warning({
        message: `表单验证失败`,
        description: `${firstSampleWithError}组样品：${fieldTitle} 不能为空`, // ✅ 包含样品组信息
        placement: 'top',
        duration: 2,
      });
      return;
    }

    // ✅ 没有错误，收集所有样品的表单数据
    const allFormData = this.state.samplesData.map((sample) => sample.formData);
    console.log('提交数据:', allFormData);

    // ✅ 整理提交数据结构
    const submitData = {
      deviceId: this.state.deviceInfo?.id,
      samplesCount: this.state.samplesData.length,
      samplesData: this.state.samplesData.map((sample) => ({
        sampleId: sample.sampleId,
        formData: sample.formData,
      })),
      totalPrice: this.state.totalPrice,
    };

    console.log('最终提交数据:', submitData);

    // ✅ 实际提交逻辑（可以调用API）
    // this.dataSourceMap['submitOrder']?.load(submitData)
    //   .then(res => {
    //     if (res.code === 1000) {
    //       this.utils.message.success('订单提交成功！');
    //       // 可以跳转到订单详情页面
    //     } else {
    //       this.utils.message.error('订单提交失败：' + res.message);
    //     }
    //   })
    //   .catch(error => {
    //     this.utils.message.error('网络错误，请重试');
    //   });
  }

  /**
   * 表单验证
   */
  formVerification() {
    const allErrors = {};
    let hasAnyError = false;

    this.state.samplesData.forEach((sample, index) => {
      const errors = {};
      const { required = [] } = this.state.testSchema;

      required.forEach((fieldName) => {
        const fieldSchema = this.state.testSchema.properties[fieldName];

        // ✅ 检查字段在当前样品中是否可见
        let isVisible = true;

        // ✅ 检查当前样品的hiddenFields
        if (sample.hiddenFields[fieldName]) {
          isVisible = false;
        }

        // 检查被动型联动是否隐藏了该字段
        if (fieldSchema.independentMode) {
          // ✅ 使用当前样品的formData
          isVisible = this.evaluateIndependentField(
            fieldSchema,
            sample.formData
          );
        }

        // 只验证可见的字段
        if (isVisible) {
          // ✅ 使用当前样品的formData
          const value = sample.formData[fieldName];
          if (
            value === undefined ||
            value === null ||
            value === '' ||
            (Array.isArray(value) && value.length === 0)
          ) {
            const fieldTitle = fieldSchema?.title || fieldName;
            errors[fieldName] = `${fieldTitle} 不能为空`;
            hasAnyError = true; // ✅ 标记有错误
          }
        }
      });

      // ✅ 如果当前样品有错误，添加到总错误中
      if (Object.keys(errors).length > 0) {
        allErrors[sample.sampleId] = errors; // ✅ 使用样品ID作为key
      }
    });

    // ✅ 返回所有样品的验证结果
    return { allErrors, hasAnyError };
  }

  /**
   * 计算价格
   */
  calculateThePrice() {
    // ✅ 不需要参数，计算所有样品的价格
    // ✅ 收集所有样品的可见字段数据
    const allVisibleFormData = this.state.samplesData.map(
      (sample, sampleIndex) => {
        const visibleFormData = {};

        Object.keys(this.state.testSchema.properties).forEach((fieldName) => {
          const fieldSchema = this.state.testSchema.properties[fieldName];
          let isVisible = true;

          if (fieldSchema.independentMode) {
            // ✅ 使用当前样品的formData
            isVisible = this.evaluateIndependentField(
              fieldSchema,
              sample.formData
            );
          } else {
            // ✅ 使用当前样品的hiddenFields
            isVisible = !sample.hiddenFields[fieldName];
          }

          // ✅ 只包含当前样品的可见字段
          if (isVisible && sample.formData[fieldName] !== undefined) {
            visibleFormData[fieldName] = sample.formData[fieldName];
          }
        });

        return visibleFormData; // ✅ 返回当前样品的可见数据
      }
    );

    // ✅ 传递所有样品的数据进行价格计算
    this.dataSourceMap['calculateprice']
      ?.load({
        id: 427,
        formData: allVisibleFormData, // ✅ 包含所有样品的可见数据
      })
      .then((res) => {
        if (res.code == 1000) {
          this.setState({
            totalPrice: res.data?.summary?.totalAmount, // ✅ 所有样品的总价格
          });
        }
      })
      .catch((error) => {
        console.error('价格计算失败:', error);
        // ✅ 可以显示错误提示
        // this.utils.message.error('价格计算失败，请重试');
      });
  }

  /**
   * 检测报价模式
   */
  testingQuotationMode(sampleIndex, fieldName, value) {
    // ✅ 添加sampleIndex参数
    const fieldSchema = this.state.testSchema.properties[fieldName];
    if (!fieldSchema || !fieldSchema.options) return;

    // ✅ 如果没有传入sampleIndex，默认使用第一个样品
    const targetSampleIndex = sampleIndex !== undefined ? sampleIndex : 0;

    // ✅ 获取指定样品的数据
    const sample = this.state.samplesData[targetSampleIndex];
    if (!sample) {
      console.error(`样品索引 ${targetSampleIndex} 不存在`);
      return;
    }

    // 单选字段：检查选中的选项
    if (fieldSchema.widget === 'select' && value) {
      const option = fieldSchema.options.find((opt) => opt.value === value);
      if (option?.is_skip === 1) {
        this.setState(
          {
            isSkipTitle: option.title,
            // ✅ 可以添加样品信息到状态中
            skipSampleId: sample.sampleId, // 记录是哪个样品需要报价
          },
          () => {
            this.$('modal')?.open();
          }
        );
      }
    }

    // 多选字段：检查新增的选项
    else if (fieldSchema.widget === 'checkboxes' && Array.isArray(value)) {
      // ✅ 使用指定样品的formData获取旧值
      const oldValue = sample.formData[fieldName] || [];
      const newOptions = value.filter((v) => !oldValue.includes(v)); // 找出新增的选项

      newOptions.forEach((optionValue) => {
        const option = fieldSchema.options.find(
          (opt) => opt.value === optionValue
        );
        if (option?.is_skip === 1) {
          this.setState(
            {
              isSkipTitle: option.title,
              // ✅ 记录样品信息
              skipSampleId: sample.sampleId, // 记录是哪个样品需要报价
            },
            () => {
              this.$('modal')?.open();
            }
          );
        }
      });
    }
  }

  /**
   * createInitialFormData
   */
  createInitialFormData() {
    const formData = {};
    const { properties = {} } = this.state.testSchema;

    Object.keys(properties).forEach((fieldName) => {
      const fieldSchema = properties[fieldName];

      if (
        fieldSchema.default !== undefined &&
        fieldSchema.default !== null &&
        fieldSchema.default !== ''
      ) {
        formData[fieldName] = fieldSchema.default;
      } else {
        switch (fieldSchema.widget) {
          case 'input':
            formData[fieldName] = '';
            break;
          case 'inputNumber':
            formData[fieldName] = '';
            break;
          case 'select':
            if (fieldSchema.options) {
              const preSelectedOption = fieldSchema.options.find(
                (opt) => opt.is_selected === 1
              );
              formData[fieldName] = preSelectedOption
                ? preSelectedOption.value
                : '';
            } else {
              formData[fieldName] = '';
            }
            break;
          case 'checkboxes':
            if (fieldSchema.options) {
              const preSelectedValues = fieldSchema.options
                .filter((opt) => opt.is_selected === 1)
                .map((opt) => opt.value);
              formData[fieldName] = preSelectedValues;
            } else {
              formData[fieldName] = [];
            }
            break;
          case 'periodicTable':
            formData[fieldName] = ['C'];
            break;
          case 'file':
            formData[fieldName] = [];
            break;
          case 'richText':
            formData[fieldName] = '';
            break;
          default:
            if (fieldSchema.type === 'number') {
              // formData[fieldName] = 1;
            } else if (fieldSchema.type === 'array') {
              formData[fieldName] = [];
            } else {
              formData[fieldName] = '';
            }
        }
      }
    });

    return formData;
  }

  /**
   * 新增样品
   */
  newSamples() {
    const newIndex = this.state.samplesData.length;
    const newSampleId = String.fromCharCode(65 + newIndex); // A, B, C, D...

    const formData = this.createInitialFormData();
    const periodicTableField = Object.keys(
      this.state.testSchema.properties || {}
    ).find(
      (key) => this.state.testSchema.properties[key].widget === 'periodicTable'
    );

    const newSample = {
      index: newIndex,
      sampleId: newSampleId,
      formData: formData,
      obtainFormData: [],
      yuansu: formData[periodicTableField] || ['C'],
      hiddenFields: {},
      validationErrors: {},
    };

    this.setState(
      {
        samplesData: [...this.state.samplesData, newSample],
      },
      () => {
        this.obtainFormData(newIndex);
        this.calculateThePrice();
        this.handleTheLinkageRules(newIndex, formData, formData);
      }
    );
  }

  /**
   * 删除样品
   */
  deleteTheSample(indexToRemove) {
    if (this.state.samplesData.length <= 1) {
      this.utils.message.warning('至少需要保留一个样品组');
      return;
    }

    // 删除指定样品
    const filteredSamples = this.state.samplesData.filter(
      (sample, index) => index !== indexToRemove
    );

    // 重新排序 A, B, C...
    const reorderedSamples = filteredSamples.map((sample, index) => ({
      ...sample,
      index: index,
      sampleId: String.fromCharCode(65 + index),
    }));

    this.setState(
      {
        samplesData: reorderedSamples,
      },
      () => {
        // 重新获取所有样品的表单数据
        reorderedSamples.forEach((sample, index) => {
          this.obtainFormData(index);
        });
        this.calculateThePrice();
      }
    );
  }

  render() {
    return (
      <Page className="flex flex-col">
        <Modal
          animate="pop"
          renderView={(props) => (
            <View className="flex flex-col bg-[#fff] h-[200px] w-[450px] rounded-[5px] pb-[20px] relative">
              <View
                onClick={(e) => {
                  this.$('modal')?.close();
                }}
                className="absolute top-[10px] right-[10px] pt-[5px] pb-[5px] pl-[5px] pr-[5px]"
              >
                <AtIcon
                  color="#666"
                  size={20}
                  svg="&#60;svg xmlns=&#34;http://www.w3.org/2000/svg&#34; width=&#34;100%&#34; height=&#34;100%&#34; viewBox=&#34;0 0 24 24&#34;&#62;&#60;path fill=&#34;currentColor&#34; fill-rule=&#34;evenodd&#34; d=&#34;m12 10.586l6.293-6.293l1.414 1.414L13.414 12l6.293 6.293l-1.414 1.414L12 13.414l-6.293 6.293l-1.414-1.414L10.586 12L4.293 5.707l1.414-1.414z&#34; clip-rule=&#34;evenodd&#34;/&#62;&#60;/svg&#62;"
                />
              </View>
              <View className="flex flex-row pt-[20px] pb-[20px] items-center justify-center">
                <View className="mr-[10px]">
                  <AtIcon
                    color="#ff9e00"
                    size={30}
                    svg="&#60;svg xmlns=&#34;http://www.w3.org/2000/svg&#34; width=&#34;100%&#34; height=&#34;100%&#34; viewBox=&#34;0 0 24 24&#34;&#62;&#60;g fill=&#34;none&#34;&#62;&#60;path d=&#34;m12.594 23.258l-.012.002l-.071.035l-.02.004l-.014-.004l-.071-.036q-.016-.004-.024.006l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.016-.018m.264-.113l-.014.002l-.184.093l-.01.01l-.003.011l.018.43l.005.012l.008.008l.201.092q.019.005.029-.008l.004-.014l-.034-.614q-.005-.019-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.003-.011l.018-.43l-.003-.012l-.01-.01z&#34; fill=&#34;currentColor&#34;/&#62;&#60;path fill=&#34;currentColor&#34; d=&#34;M6 7a5 5 0 1 1 10 0A5 5 0 0 1 6 7m-1.178 7.672C6.425 13.694 8.605 13 11 13q.671 0 1.316.07a1 1 0 0 1 .72 1.557A5.97 5.97 0 0 0 12 18c0 .92.207 1.79.575 2.567a1 1 0 0 1-.89 1.428L11 22c-2.229 0-4.335-.14-5.913-.558c-.785-.208-1.524-.506-2.084-.956C2.41 20.01 2 19.345 2 18.5c0-.787.358-1.523.844-2.139c.494-.625 1.177-1.2 1.978-1.69ZM18 14a1 1 0 0 1 1 1v3a1 1 0 1 1-2 0v-3a1 1 0 0 1 1-1m0 6a1 1 0 0 0-.117 1.993l.119.007a1 1 0 0 0 .117-1.993z&#34;/&#62;&#60;/g&#62;&#60;/svg&#62;"
                  />
                </View>
                <View>
                  <Text
                    children="提示"
                    className="text-[15px] text-[#333] font-bold"
                  />
                </View>
              </View>
              <View className="flex flex-row justify-center flex-1 items-center pl-[20px] pr-[20px]">
                <View className="inline-block">
                  <Text children="若选" className="text-sm text-[#666666]" />
                  <Text
                    children={this.state.isSkipTitle}
                    _unsafe_MixedSetter_children_select="VariableSetter"
                    className="text-sm text-[#666666]"
                  />
                  <Text
                    children="，则订单为报价模式，提交订单后我们将为您报价"
                    className="text-sm text-[#666666] [lineHeight:20px]"
                  />
                </View>
              </View>
              <View className="flex flex-row justify-center mt-[40px]">
                <View
                  className="admin-theme pt-[6px] pb-[6px] pl-[20px] pr-[20px] rounded-[5px]"
                  _unsafe_classNameJson={[{ selector: 'admin-theme' }]}
                  onClick={(e) => {
                    this.$('modal')?.close();
                  }}
                >
                  <Text children="知道了" className="text-sm text-[#ffffff]" />
                </View>
              </View>
            </View>
          )}
          visible={false}
          maskClosable={true}
          ref="modal"
          className=""
        />
        <View className="w-[1000px]">
          {!!false && (
            <View className="mb-[20px] flex flex-row bg-[#ffffff]">
              <View
                className="admin-theme pt-[10px] pb-[10px] flex flex-col items-center"
                _unsafe_classNameJson={[{ selector: 'admin-theme' }]}
              >
                <View>
                  <Text
                    children="下单：同步辐射吸收谱之硬X射线"
                    className="text-sm text-[#ffffff] pl-[12px] pr-[12px]"
                  />
                </View>
              </View>
              <View className="pt-[10px] pb-[10px] flex flex-col items-center bg-[#d9d9d9]">
                <View>
                  <Text
                    children="仪器详情"
                    className="text-sm text-[#666666] pl-[12px] pr-[12px]"
                  />
                </View>
              </View>
              <View className="pt-[10px] pb-[10px] flex flex-col items-center bg-[#d9d9d9]">
                <View>
                  <Text
                    children="测试案例"
                    className="text-sm text-[#666666] pl-[12px] pr-[12px]"
                  />
                </View>
              </View>
              <View className="pt-[10px] pb-[10px] flex flex-col items-center bg-[#d9d9d9]">
                <View>
                  <Text
                    children="样品要求"
                    className="text-sm text-[#666666] pl-[12px] pr-[12px]"
                  />
                </View>
              </View>
              <View className="pt-[10px] pb-[10px] flex flex-col items-center bg-[#d9d9d9]">
                <View>
                  <Text
                    children="常见问题"
                    className="text-sm text-[#666666] pl-[12px] pr-[12px]"
                  />
                </View>
              </View>
            </View>
          )}
          {!!false && (
            <View className="mb-[20px] h-[400px]">
              <View className="h-[40px] border-b-[1px] border-b-solid border-b-[#d9d9d9] flex flex-row items-center pl-[20px] pr-[20px]">
                <View className="flex-1">
                  <Text
                    children="预约须知"
                    className="text-base text-[#333] font-bold"
                  />
                </View>
                <View>
                  <AtIcon
                    color="#666"
                    size={24}
                    svg="&#60;svg xmlns=&#34;http://www.w3.org/2000/svg&#34; width=&#34;100%&#34; height=&#34;100%&#34; viewBox=&#34;0 0 24 24&#34;&#62;&#60;path fill=&#34;none&#34; stroke=&#34;currentColor&#34; stroke-linecap=&#34;round&#34; stroke-linejoin=&#34;round&#34; stroke-width=&#34;2&#34; d=&#34;m4 9l8 8l8-8&#34;/&#62;&#60;/svg&#62;"
                  />
                </View>
              </View>
            </View>
          )}
          <View className="w-[1000px]">
            <View
              __hidePh={true}
              className="w-[1200px] bg-[#ffffff] pt-[40px] pl-[20px] pr-[20px] flex flex-col"
            >
              <View className="flex flex-row items-center">
                <View className="flex flex-row w-[121px] justify-start">
                  <View>
                    <Text children="*" className="text-sm text-[#f56c6c]" />
                  </View>
                  <View className="mr-[15px] ml-[5px]">
                    <Text
                      children="样品名称"
                      className="text-[15px] text-[#666666] font-medium"
                    />
                  </View>
                </View>
                <View className="flex-1">
                  <Input
                    value="1"
                    bordered={true}
                    disabled={false}
                    placeholder=""
                    size="large"
                    className="w-[500px] h-[36px]"
                  />
                </View>
              </View>
              <View className="flex flex-row items-center mt-[12px] mb-[20px]">
                <View className="flex flex-row items-center w-[121px] justify-start">
                  <View>
                    <Text children="*" className="text-sm text-[#f56c6c]" />
                  </View>
                  <View className="mr-[15px] ml-[5px]">
                    <Text
                      children="已沟通工程师"
                      className="text-[15px] text-[#666666] font-medium"
                    />
                  </View>
                </View>
                <View className="">
                  <Input
                    bordered={true}
                    disabled={false}
                    placeholder=""
                    size="large"
                    className="w-[500px] h-[36px]"
                  />
                </View>
                <View className="ml-[10px]">
                  <Text
                    children="若无沟通工程师，请填写无"
                    className="text-sm text-[#fea000]"
                  />
                </View>
              </View>
              {this.state.samplesData.map((sample, sampleIndex) => (
                <View __hidePh={true}>
                  <View>
                    <View className="pb-[80px]">
                      <View className="relative">
                        <View animationIn="" className="">
                          {sample?.obtainFormData
                            ?.slice(1, sample?.obtainFormData?.length + 1)
                            .map((item, index) => (
                              <View className="flex flex-col mb-[40px] pl-[20px]">
                                <View>
                                  <View className="mr-[15px] flex-1 flex flex-row items-center">
                                    {!!(
                                      item?.fieldSchema?.widget ==
                                      'periodicTable'
                                    ) && (
                                        <View
                                          _unsafe_MixedSetter____condition____select="VariableSetter"
                                          className="flex flex-row items-center flex-1"
                                        >
                                          <View className="flex-1 flex flex-row">
                                            <Text
                                              children="您已选择了："
                                              className="text-sm text-[#666666] font-normal"
                                            />
                                            <Text
                                              children={
                                                (this.state.samplesData[
                                                  sampleIndex
                                                ]?.yuansu?.join('、') || 'C') +
                                                `共${this.state.samplesData[
                                                  sampleIndex
                                                ]?.yuansu?.length || 1
                                                }个元素`
                                              }
                                              _unsafe_MixedSetter_children_select="VariableSetter"
                                              className="text-sm text-[#333333] font-bold"
                                            />
                                          </View>
                                          <View
                                            className="option-item-active h-[32px] flex flex-col justify-center items-center min-w-[80px] pl-[12px] pr-[12px]"
                                            _unsafe_classNameJson={[
                                              { selector: 'option-item-active' },
                                            ]}
                                            onClick={(e) => {
                                              const { item, index } = this;
                                              this.utils.showComponentModal(
                                                'PeriodicTableComponent',
                                                {
                                                  value:
                                                    this.state.samplesData[
                                                      sampleIndex
                                                    ]?.yuansu || [],
                                                  onChange: (value) => {
                                                    console.log(
                                                      Array.from(value)
                                                    );
                                                    const selectedElements =
                                                      Array.from(value);

                                                    const newSamplesData =
                                                      this.state.samplesData.map(
                                                        (sample, index) => {
                                                          if (
                                                            index === sampleIndex
                                                          ) {
                                                            // 使用动态的sampleIndex
                                                            return {
                                                              ...sample,
                                                              yuansu:
                                                                selectedElements,
                                                            };
                                                          }
                                                          return sample;
                                                        }
                                                      );

                                                    this.setState(
                                                      {
                                                        samplesData:
                                                          newSamplesData, // ✅ 更新samplesData数组
                                                      },
                                                      () => {
                                                        this.handleInputChange({
                                                          sampleIndex:
                                                            sampleIndex, // 使用动态的sampleIndex
                                                          fieldName:
                                                            item?.fieldName,
                                                          value: selectedElements, // ✅ 使用选择的元素数组
                                                        });
                                                      }
                                                    );
                                                  },
                                                },
                                                {
                                                  animate: 'pop',
                                                  style: {
                                                    height: '60%',
                                                  },
                                                }
                                              );
                                            }}
                                          >
                                            <Text
                                              children="选择元素"
                                              className="text-sm"
                                            />
                                          </View>
                                        </View>
                                      )}
                                  </View>
                                </View>
                              </View>
                            ))}
                        </View>
                      </View>
                    </View>
                  </View>
                </View>
              ))}
              <View>
                <Button
                  type="primary"
                  children="添加样品"
                  htmlType="button"
                  size="middle"
                  shape="default"
                  block={false}
                  danger={false}
                  ghost={false}
                  disabled={false}
                  onClick={(event) => this.newSamples()}
                />
              </View>
            </View>
            <View className="w-[1000px] h-[60px] bg-[rgba(51,119,254,0.2)]">
              <Button
                type="primary"
                children="下一步"
                htmlType="button"
                size="middle"
                shape="default"
                block={false}
                danger={false}
                ghost={false}
                disabled={false}
                onClick={(event) => this.submitForm(event)}
              />
            </View>
          </View>
        </View>
      </Page>
    );
  }
}

export default Document;
